﻿using Core.SimpleTemp.Common;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Core.SimpleTemp.Application.Common
{
    /// <summary>
    /// 部门人员下拉树类型
    /// </summary>
    public enum DepartmentType : byte
    {
        /// <summary>
        /// 查询所有
        /// </summary>
        All = 0,
        /// <summary>
        /// 只查询隐患确认人及对应的部门
        /// </summary>
        Ensure = 1,
        /// <summary>
        /// 只查询隐患负责人及对应的部门
        /// </summary>
        PersonInCharge = 2,
        /// <summary>
        /// 只查询隐患整改人及对应的部门
        /// </summary>
        Rectification = 3
    }
    [AutoDi]
    public class DepartmentStaffService
    {
        CoreDBContext _coreDbContext;
        SQLHelper _sQLHelper;
        public DepartmentStaffService(CoreDBContext coreDbContext, SQLHelper sQLHelper)
        {
            _coreDbContext = coreDbContext;
            _sQLHelper = sQLHelper;
        }


        /// <summary>
        /// 获取已部门为层级的用户数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetData(DepartmentType departmentType = DepartmentType.All, Guid? FactoryId = null)
        {
            string sqlStr = "";
            switch (departmentType)
            {
                case DepartmentType.All:
                    break;
                case DepartmentType.Ensure:
                    sqlStr = " where ui.IsEnsure='true' ";
                    break;
                case DepartmentType.PersonInCharge:
                    sqlStr = " where ui.IsPersonInCharge='true' ";
                    break;
                case DepartmentType.Rectification:
                    sqlStr = " where ui.IsRectification='true' ";
                    break;
                default:
                    break;
            }
            string factorySqlStr1 = "";
            string factorySqlStr2 = "";
            if (FactoryId != null)
            {
                factorySqlStr1 = " and  ui.WorkCompany='" + FactoryId + "'";
                factorySqlStr2 = " and  CreateFactory='" + FactoryId + "'";
            }

            //用户信息与部门信息UnionAll成数据集，（把用户信息当初部门子数据处理）
            //            string sql = @"SELECT  * FROM (
            //SELECT   U.Id id,U.Name label ,d.Id ParentId ,1 AS T FROM  SysDepartment d
            //							inner join SysUserDepartmentDuty udd on udd.SysDepartmentID=d.Id
            //                            inner JOIN  SysUser u  ON  udd.SysUserInforID =u.Id
            //							inner join SysUserInfor ui on u.Id=ui.SysUserID
            //							 where 1=1 " + factorySqlStr1 + @"
            //							 ) AS TABLE1 group by TABLE1.id,TABLE1.label,TABLE1.ParentId,table1.T 
            //                            UNION ALL
            //                            select  ID,Name label ,ParentId ,0 AS T from SysDepartment where 1=1 " + factorySqlStr2;
            string sql = @"SELECT  * FROM (SELECT   U.Id id,U.Name label ,d.Id ParentId ,1 AS T FROM  SysDepartment d
inner join SysDuty du on du.SysDepartmentID=d.Id
							inner join SysUserDuty ud on ud.SysDutyID=du.Id
                            inner JOIN  SysUser u  ON  ud.SysUserId =u.Id
							inner join SysUserInfor ui on u.Id=ui.SysUserID
							 where 1=1 " + factorySqlStr1 + @"
							 ) AS TABLE1 group by TABLE1.id,TABLE1.label,TABLE1.ParentId,table1.T 
                            UNION ALL
                            select  ID,Name label ,ParentId ,0 AS T from SysDepartment where 1=1 " + factorySqlStr2;
            //查询
            var dataTable = _sQLHelper.ExecuteDataTable(sql, null);
            //移除没有用户的部门信息
            ChangeData(ref dataTable);
            return dataTable;
        }

        /// <summary>
        /// 移除没有用户的部门信息
        /// </summary>
        /// <param name="dataTable"></param>
        private void ChangeData(ref DataTable dataTable)
        {
            //查询出部门数据
            var rowDepartmentList = dataTable.Select("T=0");
            //保存没有用户的部门ID
            var noSubdataList = new List<object>();

            //查询出没有用户的部门ID
            foreach (var item in rowDepartmentList)
            {
                var noSubDataId = item["id"];
                var subdata = dataTable.Select("parentId='" + Convert.ToString(noSubDataId) + "'");
                if (subdata == null || !subdata.Any())
                    noSubdataList.Add(noSubDataId);
            }
            //移除没有用户的部门信息
            for (int i = dataTable.Rows.Count - 1; i >= 0; i--)
            {
                if (noSubdataList.Contains(dataTable.Rows[i]["id"]))
                    dataTable.Rows.RemoveAt(i);
            }


        }

        /// <summary>
        /// 获取已部门为层级的双总部用户数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetDataDouble(DepartmentType departmentType = DepartmentType.All)
        {
            string sqlStr = "";
            switch (departmentType)
            {
                case DepartmentType.All:
                    break;
                case DepartmentType.Ensure:
                    sqlStr = " where ui.IsEnsure='true' ";
                    break;
                case DepartmentType.PersonInCharge:
                    sqlStr = " where ui.IsPersonInCharge='true' ";
                    break;
                case DepartmentType.Rectification:
                    sqlStr = " where ui.IsRectification='true' ";
                    break;
                default:
                    break;
            }
            //用户信息与部门信息UnionAll成数据集，（把用户信息当初部门子数据处理）
            string sql = @"SELECT  * FROM (SELECT   UI.SysUserID id,ui.Name label ,d.Id ParentId ,1 AS T FROM  SysDepartment D
                            inner JOIN SysDepartmentDuty  DD ON  D.Id= DD.SysDepartmentID
                            inner JOIN SysUserDuty  UD ON DD.Id=UD.SysDepartmentDutyId
                            inner JOIN  SysUser U  ON  UD.SysUserId =U.Id
                            inner Join SysUserInfor ui on  u.Id=ui.SysUserID and ui.IsBoth=1 " + sqlStr + @" ) AS TABLE1 group by TABLE1.id,TABLE1.label,TABLE1.ParentId,table1.T 
                            UNION ALL
                            select  ID,Name label ,ParentId ,0 AS T from SysDepartment";
            //查询
            var dataTable = _sQLHelper.ExecuteDataTable(sql, null);
            //移除没有用户的部门信息
            ChangeData(ref dataTable);
            return dataTable;
        }
        ///////////////

    }
}
